//
//  UITableView+Refresh.m
//  LotteryClient
//
//  Created by Sunyon 14-4-24.
//  Copyright (c) 2014年 CTTC. All rights reserved.
//

#import "UITableView+Refresh.h"
#import "UIColor+BaseFramework.h"
#import <objc/runtime.h>

#define kStatueLabelInFootViewTag 2000
#define kIndicatorViewInFootViewTag 2010

#define SetMyIntVar(key, value)\
objc_setAssociatedObject(self,#key, [NSString stringWithFormat:@"%d",value], OBJC_ASSOCIATION_RETAIN_NONATOMIC)

#define GetMyIntVar(key) \
[objc_getAssociatedObject(self, #key) integerValue]

@implementation UITableView (Refresh)

static char *openRefreshKey = "isOpenRefreshKey";

static char *refreshHeaderViewKey = "refreshHeaderViewKey";

static char *refreshingKey = "refreshingKey";

static char *loadingMoreKey = "loadingMoreKey";

#pragma mark- 获取下拉刷新状态

- (BOOL)isRefreshing
{
    NSString *_isRefreshing = objc_getAssociatedObject(self, refreshingKey);
    return _isRefreshing &&
           [_isRefreshing isEqualToString:@"YES"];
}

- (BOOL)isLoadingMore
{
    NSString *_isRefreshing = objc_getAssociatedObject(self, loadingMoreKey);
    return _isRefreshing &&
           [_isRefreshing isEqualToString:@"YES"];
}


#pragma mark- 获取当前tableview是否 使用了下拉刷新功能

- (BOOL)isOpenRefreshFun
{
    NSString *_isOpenRefreshFun = objc_getAssociatedObject(self, openRefreshKey);
    return _isOpenRefreshFun &&
           [_isOpenRefreshFun isEqualToString:@"YES"];
}

#pragma mark- 设置是否使用下拉刷新方法

- (void)setIsOpenRefreshFun:(BOOL)isOpenRefreshFun
{
    if (isOpenRefreshFun)
    {
        EGORefreshTableHeaderView *refreshView = objc_getAssociatedObject(self, refreshHeaderViewKey);
        if (!refreshView)
        {
            refreshView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f,
                                                                                      0.0f - self.frame.size.height,
                                                                                      self.frame.size.width,
                                                                                      self.bounds.size.height)];
            objc_setAssociatedObject(self, refreshHeaderViewKey, refreshView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            refreshView.delegate = (id <EGORefreshTableHeaderDelegate>) self;
            [self addSubview:refreshView];

        }

        objc_setAssociatedObject(self, openRefreshKey, @"YES", OBJC_ASSOCIATION_RETAIN_NONATOMIC);

        IMP impx = [[self class] instanceMethodForSelector:@selector(scrollViewDidEndDragging:willDecelerate:)];

        class_addMethod([self.delegate class], @selector(scrollViewDidEndDragging:willDecelerate:), impx, "v@:@i");

        [self addObserver:self
               forKeyPath:@"contentOffset"
                  options:NSKeyValueObservingOptionNew
                  context:nil];

    }
    else
    {

        EGORefreshTableHeaderView *refreshView = objc_getAssociatedObject(self, refreshHeaderViewKey);
        if (refreshView)
        {
            [refreshView removeFromSuperview];
//            [refreshView release];
        }

        [self removeObserver:self
                  forKeyPath:@"contentOffset"];

        objc_setAssociatedObject(self, openRefreshKey, @"NO", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        objc_setAssociatedObject(self, refreshHeaderViewKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    }
}


- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    [self scrollViewDidScroll:self];
}


#pragma mark- 获取下拉刷新视图

- (EGORefreshTableHeaderView *)refreshHeaderView
{
    return objc_getAssociatedObject(self, refreshHeaderViewKey);

}


#pragma mark- 下拉刷新完毕调用

- (void)finishLoadingTableViewData
{
    [self EGORefreshDone];

    [self finishLoadMoreTableViewData];

}

#pragma mark- 加载跟多完毕时调用

- (void)finishLoadMoreTableViewData
{
    if (self.tableFooterView)
    {
        if ([self.tableFooterView isKindOfClass:[UIButton class]])
        {
            [(UIButton *) self.tableFooterView setEnabled:YES];
        }
        else
        {
            UILabel *label = (UILabel *) [self.tableFooterView viewWithTag:kStatueLabelInFootViewTag];
            label.text = @"上拉加载更多";
        }
        UIActivityIndicatorView *view = (UIActivityIndicatorView *) [self.tableFooterView viewWithTag:kIndicatorViewInFootViewTag];
        [view stopAnimating];
    }

    objc_setAssociatedObject(self, loadingMoreKey, @"NO", OBJC_ASSOCIATION_RETAIN_NONATOMIC);


}


#pragma mark- 获取loadMoreStyle

- (UITableViewLoadMoreStyle)loadMoreStyle
{
    return (UITableViewLoadMoreStyle) GetMyIntVar(loadMoreStyleKey);
}

#pragma mark- 设置loadMoreStyle

- (void)setLoadMoreStyle:(UITableViewLoadMoreStyle)loadMoreStyle
{
    SetMyIntVar(loadMoreStyleKey, loadMoreStyle);

    switch (loadMoreStyle)
    {
        case UITableViewLoadMoreStyleNon:   //不使用或者禁用加载更多功能
        {
            self.tableFooterView = nil;
            break;
        }
        case UITableViewLoadMoreStyle1:      //使用上拉加载更多数据功能
        {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, 30)];

            UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            activityView.frame = CGRectMake(25.0f, 5, 20.0f, 20.0f);
            activityView.tag   = kIndicatorViewInFootViewTag;
            [view addSubview:activityView];

            view.backgroundColor = [UIColor lightGrayColor];

            UILabel *label = [[UILabel alloc] initWithFrame:view.frame];
            label.backgroundColor = [UIColor colorWithHexString:@"ecece4"];
            label.tag             = kStatueLabelInFootViewTag;
            label.text            = @"上拉加载更多";
            [label setTextColor:[UIColor grayColor]];
            label.font = [UIFont systemFontOfSize:14];
            [view addSubview:label];
            label.textAlignment = NSTextAlignmentCenter;

            self.tableFooterView = view;
            break;
        }
        case UITableViewLoadMoreStyle2:      //使用点击加载更多数据功能
        {
            UIButton *loadMoreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [loadMoreBtn setTitle:@"点击加载更多"
                         forState:UIControlStateNormal];
            [loadMoreBtn setTitle:@"加载中..."
                         forState:UIControlStateDisabled];

            [loadMoreBtn addTarget:self
                            action:@selector(clickLoadMoreBtn)
                  forControlEvents:UIControlEventTouchUpInside];
            loadMoreBtn.frame = CGRectMake(0, 0, 320, 30);
            [loadMoreBtn setTitleColor:[UIColor blackColor]
                              forState:UIControlStateNormal];

            loadMoreBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            loadMoreBtn.backgroundColor = [UIColor lightGrayColor];

            UIActivityIndicatorView *view = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            view.frame = CGRectMake(25.0f, 5, 20.0f, 20.0f);
            view.tag   = kIndicatorViewInFootViewTag;
            [loadMoreBtn addSubview:view];

            self.tableFooterView = loadMoreBtn;

            break;
        }
        default:
        {
            self.tableFooterView = nil;
            break;
        }
    }

}

#pragma mark- 加载更多方法

- (void)clickLoadMoreBtn
{
    objc_setAssociatedObject(self, loadingMoreKey, @"YES", OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    //如果时点击加载更多
    if ([self.tableFooterView isKindOfClass:[UIButton class]])
    {
        [(UIButton *) self.tableFooterView setEnabled:NO];
    }

    UIActivityIndicatorView *view = (UIActivityIndicatorView *) [self.tableFooterView viewWithTag:kIndicatorViewInFootViewTag];
    [view startAnimating];


	WEAKSELF;
	dispatch_async(dispatch_get_main_queue(), ^{
		STRONGSELF;
		if ([strongSelf respondsToSelector:@selector(doneLoadMoreData:)])
		{
			[(id<UITableViewRefreshDelegate>)strongSelf.delegate  doneLoadMoreData:self];
		}
		
	});
	

}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view
{

    objc_setAssociatedObject(self, refreshingKey, @"YES", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    //开始刷新后执行后台线程，在此之前可以开启HUD或其他对UI进行阻塞


    [NSThread detachNewThreadSelector:@selector(doInBackground)
                             toTarget:self
                           withObject:nil];

}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view
{

    return [self isRefreshing];
}

- (NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view
{
    return [NSDate date];
}


- (void)EGORefreshDone
{
    objc_setAssociatedObject(self, refreshingKey, @"NO", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [[self refreshHeaderView] egoRefreshScrollViewDataSourceDidFinishedLoading:self];
}

#pragma mark- 下拉刷新方法

- (void)doInBackground
{
//    [self.delegate performSelectorOnMainThread:@selector(doneLoadingTableViewData:)
//                                    withObject:self
//                                 waitUntilDone:NO];
	
	WEAKSELF;
	dispatch_async(dispatch_get_main_queue(), ^{
		STRONGSELF;
		if ([strongSelf.delegate respondsToSelector:@selector(doneLoadingTableViewData:)])
		{
			[(id<UITableViewRefreshDelegate>)strongSelf.delegate  doneLoadingTableViewData:self];
		}
		
	});
}

#pragma mark- 手动调用下拉刷新方法

- (void)refreshTable
{
    [self setContentOffset:CGPointMake(0, -65)
                  animated:NO];
    [self scrollViewDidEndDragging:self
                    willDecelerate:NO];

}


#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
	if (![scrollView isKindOfClass:[UITableView class]])
   {
	   return;
	}
    //下啦刷新 功能方法
    if ([(UITableView *) scrollView isOpenRefreshFun])
    {
        [[(UITableView *) scrollView refreshHeaderView] egoRefreshScrollViewDidScroll:scrollView];
    }

    //上拉加载更多 功能方法
    UITableViewLoadMoreStyle style = [(UITableView *) scrollView loadMoreStyle];

    if (style == UITableViewLoadMoreStyle1)
    {

        UIActivityIndicatorView *view = (UIActivityIndicatorView *) [self.tableFooterView viewWithTag:kIndicatorViewInFootViewTag];
        if (!view.isAnimating)
        {
            UILabel *label = (UILabel *) [self.tableFooterView viewWithTag:kStatueLabelInFootViewTag];
            if (scrollView.contentOffset.y + scrollView.frame.size.height > scrollView.contentSize.height + 30)
            {

                label.text = @"释放加载更多";
            }
            else
            {
                label.text = @"上拉加载更多";

            }

        }


    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView
                  willDecelerate:(BOOL)decelerate
{
	
	if (![scrollView isKindOfClass:[UITableView class]])
	{
		return;
	}
    //下啦刷新 功能方法
    if ([(UITableView *) scrollView isOpenRefreshFun])
    {
        [[(UITableView *) scrollView refreshHeaderView] egoRefreshScrollViewDidEndDragging:scrollView];

    }
    //上拉加载更多 功能方法

    UITableViewLoadMoreStyle style = [(UITableView *) scrollView loadMoreStyle];

    if (style == UITableViewLoadMoreStyle1)
    {
        if (scrollView.contentOffset.y + scrollView.frame.size.height > scrollView.contentSize.height + 60)
        {
            UILabel *label = (UILabel *) [((UITableView *) scrollView).tableFooterView viewWithTag:kStatueLabelInFootViewTag];
            label.text = @"加载中...";

            [(UITableView *) scrollView clickLoadMoreBtn];
        }
    }
}
@end
